var fs = require('fs');
var config = require('../config');

var VandB = {
	find:function(req, type, callback){
		req.VandB.find({'type':type}).toArray(function(err, items){
			if (err) {
				callback({
					status:400,
					dt:err
				})
			} else {
				callback({
					status:200,
					dt:items
				})
			}
		})
	},
	findId:function(req, id, callback){
		req.VandB.findIdById(id, function(err, result){
			if (err) {
				callback('bad req')
			} else {
				callback(result)
			}
		})
	},
	findArr:function(req, idArr, callback){
		for (var i = 0; i < idArr.length; i++) {
			idArr[i] = req.dbid(idArr[i])
		}
		req.VandB.find({
				'_id':{
					$in:idArr
				}
			}, {
				_id:1,
				name:1,
				info:1,
				img:1,
				tag:1,
				upUser:1
			}).toArray(function(err, items){
				if (err) {
					callback('items err'+err)
				} else {
					callback(items)
				}
			})
	},
	findTag:function(req, tag, callback){
		req.VandB.find({
			'tag':tag,
			'pass':true
		}).toArray(function(err, items){
			if (err) {
				callback({'status':400,'dt':err})
			} else {
				callback({'status':400,'dt':items})
			}
		})
	},
	findByUpuser:function(req, type, upId, callback){
		req.VandB.find({
			'upUser':upId,
			'type':type
		}).toArray(function(err, items){
			if (err) {
				
			} else {
				callback(items)
			}
		})
	},
	delete:function(req, type, id, path, callback){
		switch(type){
			case 'video':{
				req.VandB.update({
					'_id':id,
					'type':'video',
				},{
					'delete':true
				}, function(err, result){
					fs.unlink(config.PATH+path, function(err){
						if (err) {
							callback({status:400, d:err})
						} else {
							callback({status:200, d:'delete success'})
						}
					})
				})
			}
			case 'article':{
				req.VandB.removeById(id, callback('delete success'))
			}
		}
		
	},
	insertArr:function(req, vData, callback){
		req.VandB.insert({
			'type':vData.type,
			'name':vData.name,
			'info':vData.info,
			'tag' :vData.tag,
			'path':[vData.pathArray],
			'img' :[vData.imgPath],
			'upUser':vData.upUser,
			'uptime':vData.uptime
		}, function(err, result){
			if (err) {

			} else {
				callback('ok')
			}
		})
	}
}

module.exports = VandB;